import 'package:flutter/material.dart';
import 'component.dart';
import 'overview_api_provider.dart';
import 'models/OverViewModel.dart';
import 'global/size_config.dart';
import 'global/event_bus.dart';

class DataScreen extends StatefulWidget {
  DataScreen({Key key})
      : super(key: key);

  @override
  _DataScreenState createState() {
    return _DataScreenState();
  }
}

class _DataScreenState extends State<DataScreen> with AutomaticKeepAliveClientMixin {
  bool get wantKeepAlive => true;
  OverViewProvider provider = OverViewProvider();
  OverViewModel model;
  bool hasError = false;
  bool isLoad = true;
  int typeIndex = 1;
  int dateIndex = 0;
  @override
  void initState() {
    super.initState();
    getOverViewData();
  }

  getOverViewData() async {
    final order = typeIndex==0 ? null : (typeIndex==1? 'H':'Z');
    //1 当前 2昨日 3 本周 4本月 5年
    final dateType = dateIndex + 1;
    isLoad = true;
    setState(() {});
    try {
      model = await provider.fetchOverView(order, dateType);
      bus.emit('nowdate', model.resObj.nowDate);
      isLoad = false;
      hasError = false;
      setState(() {});
    } catch(e) {
      hasError = true;
      isLoad = false;
      setState(() {});
    }
  }

  @override
  Widget build(BuildContext context) {
    if(isLoad) {
      return LoadingBlock();
    }
    if(hasError) {
      return ErrorBlock(errorType: ErrorType.invalidData,);
    }
    if (model == null || model.resObj == null) {
      return ErrorBlock(errorType: ErrorType.noData,);
    }
    OverViewData data = model.resObj;
    return Container(
      child: Column(
        children: <Widget>[
          Container(
            padding: const EdgeInsets.only(right: 10),
            height: 40,
            child: Row(
              mainAxisAlignment: MainAxisAlignment.end,
              children: <Widget>[
                FilterChooser(
                  filterItems: ['全部', '18基础型', '19舒适型'],
                  currentIndex: typeIndex,
                  onClick: (idx) {
                      typeIndex = idx;
                      getOverViewData();
                  },
                ),
                Padding(
                  padding: const EdgeInsets.only(left: 100),
                  child: FilterChooser(
                    currentIndex: dateIndex,
                    filterItems: ['实时', '昨日', '前日', '本周', '上周', '本月', '上月', '上上月'],
                    onClick: (idx) {
                      dateIndex = idx;
                      getOverViewData();
                    },
                  ),
                )
              ],
            ),
          ),
          Expanded(
            child: Row(
              children: <Widget>[
                Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children:
                        <Widget>[
                          /*Text(
                            '当前时间: ${data.nowDate}',
                            style: TextStyle(
                                color: Colors.white,
                              fontSize: 12,
                            ),
                          ),*/
                      Padding(
                        padding: const EdgeInsets.fromLTRB(30, 5, 0, 0),
                        child: SmallInfoView(
                          icon: 'images/info_user.png',
                          viewInfo: [
                            {'title':'总产量:','content':'${data.depositCount}'},
                            {'title':'使用部件:', 'content': '${data.totalValidAmount}'}
                            ],
                        ),
                      ),
                      Padding(
                        padding: const EdgeInsets.fromLTRB(30, 10, 0, 0),
                        child: SmallInfoView(
                          icon: 'images/info_money.png',
                          viewInfo: [
                            {'title':'进库成本:','content':'${data.totalDepositAmount}'},
                            {'title':'出库成本:', 'content': '${data.totalAtmAmount}'}
                            ],
                        ),
                      ),
                      Padding(
                        padding: const EdgeInsets.fromLTRB(30, 10, 0, 0),
                        child: SmallInfoView(
                          icon: 'images/info_income.png',
                          viewInfo: [{'title':'销售毛利:', 'content': '${data.profitAmount}'}],
                        ),
                      ),
                    ]),
                Expanded(
                  child: Padding(
                    padding: const EdgeInsets.fromLTRB(150, 10, 30, 0),
                    child: Column(
                      children: <Widget>[
                        DataRing(
                          ringTitle: '进库总额',
                          ringContent: (data.totalDepositAmount).toString(),
                          firstText: '新增总额 ${data.totalFirstAmount}',
                          secondText: '再增总额 ${data.totalSecondAmount}',
                        ),
                        SizedBox(
                          height: 8,
                        ),
                        DataRing(
                          ringTitle: '新增车辆',
                          ringContent: '${data.totalRegistCount}',
                          firstText: '新增产量 ${data.depositFirstCount}',
                          secondText: ''//'报损产量 ${data.lossCount}',
                        )
                      ],
                    ),
                  ),
                )
              ],
            ),
          )
        ],
      ),
    );
  }
}

//圆环图
const _infoTextStyle = TextStyle(
  color: Color(0xFF758BB5),
  fontSize: 12,
);

class DataRing extends StatelessWidget {
  const DataRing(
      {Key key,
      this.ringTitle,
      this.ringContent,
      this.firstText,
      this.secondText})
      : super(key: key);
  final String ringTitle;
  final String ringContent;
  final String firstText;
  final String secondText;

  @override
  Widget build(BuildContext context) {
    SizeConfig().init(context);

    return Row(
      children: <Widget>[
        Container(
          width: 100,
          height: 100,
          child: Stack(
            children: <Widget>[
              Image(
                image: AssetImage('images/data_ring.png'),
              ),
              Align(
                alignment: Alignment.center,
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: <Widget>[
                    Text(
                      ringTitle,
                      style: _infoTextStyle,
                    ),
                    Text(
                      ringContent,
                      style: _infoTextStyle,
                    )
                  ],
                ),
              )
            ],
          ),
        ),
        SizedBox(
          width: 10,
        ),
        Column(
          children: <Widget>[
            Text(
              firstText,
              style: _infoTextStyle,
            ),
            SizedBox(
              height: 20,
            ),
            Text(
              secondText,
              style: _infoTextStyle,
            )
          ],
        )
      ],
    );
  }
}
